package com.jzo2o.health.listener;

import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.service.IOrdersService;
import com.jzo2o.health.service.IReservationSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 关闭订单消费者
 *
 * @Author wangxinyi
 * @Date 2024/12/14 15:21
 */
@Component
@Slf4j
public class CloseOrderListener {


    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IReservationSettingService reservationSettingService;


    /**
     * 超时关闭订单
     *
     * @param orderId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_DELAY_QUEUE),
            exchange = @Exchange(name = TradeConstants.MQ_DELAY_EXCHANGE, delayed = "true"),
            key = TradeConstants.MQ_DELAY_KEY
    ))
    public void listenTradeUpdatePayStatusMsg(String orderId) {
        //1.判断参数是否为空
        if (orderId == null) {
            return;
        }
        //2.判断订单是否存在
        Orders orders = ordersService.getById(orderId);
        if (orders == null) {
            throw new ForbiddenOperationException("订单不存在");
        }
        //3.封装取消记录对象
        //判断订单状态是未支付才执行
        if (ObjectUtils.equals(orders.getOrderStatus(), OrderStatusEnum.NO_PAY.getStatus())) {
            //预约人数-1
            reservationSettingService.substract(orders.getReservationDate());
            ordersService.cancelForNoPay(orders.getId(), "到期未支付自动取消订单", false);
            log.info("[订单状态变更]订单超时自动取消，取消订单的id为:{}", orderId);
        }
    }
}
